package com.xaicode.learn.netty.tcpProtocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 11:30
 */
@Slf4j
public class MessageDecoder extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        log.info("MessageDecoder#decode is called");

        int length = in.readInt();
        byte[] content = new byte[length];
        in.readBytes(content);

        // to messageProtocol
        MessageProtocol messageProtocol = MessageProtocol.builder()
                .len(length)
                .content(content)
                .build();
        out.add(messageProtocol);
    }
}
